import SockJS from 'sockjs-client'
import * as Stomp from 'webstomp-client'

export default class TrackerService {
  private stompClient: Stomp.Client | undefined = undefined

  public connect(): void {
    if (this.stompClient && this.stompClient.connected) {
      return
    }
    const url = 'http://localhost:8888/websocket/tracker'
    const socket: WebSocket = new SockJS(url)
    this.stompClient = Stomp.over(socket)
    const headers: Stomp.ConnectionHeaders = {}
    this.stompClient.connect(headers, () => {
      console.log('connected success!')
    })
  }

  public send() {
    if (this.stompClient !== undefined) {
      this.stompClient.send(
        '/topic/activity',
        JSON.stringify({
          a: 1,
          b: 2
        }),
        {}
      )
    }
  }

  public subscribe() {
    if (this.stompClient !== undefined) {
      this.stompClient.subscribe('/topic/tracker', (data: Stomp.Message) => {
        console.log('===== receive data =====', data)
      })
    }
  }
}
